package org.kilian;

import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.security.GeneralSecurityException;
import java.util.HashMap;

import org.GenusApis.GenusApis;
import org.GenusApis.lib.HyvesApiException;
import org.GenusApis.lib.OAuthConsumer;
import org.GenusApis.lib.OAuthRequestToken;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class HyvesFotolijstjeAuthCallback extends Activity {

	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Uri uri = this.getIntent().getData();
        if(uri != null) {
          String access_token = uri.getQueryParameter("oauth_token");
          String secret = uri.getQueryParameter("s");
      	OAuthConsumer oauthConsumer = new OAuthConsumer(HyvesFotolijstje.CONSUMER_KEY, HyvesFotolijstje.CONSUMER_SECRET);
        GenusApis genusApis = new GenusApis(oauthConsumer, HyvesFotolijstje.HA_VERSION);
        OAuthRequestToken requestToken = new OAuthRequestToken(access_token, secret);
        try {
			JSONObject result = genusApis.doMethod("auth.accesstoken", new HashMap<String, String>(), requestToken);
			SharedPreferences settings = getSharedPreferences(HyvesFotolijstje.PREF_TOKEN, 0);
			SharedPreferences.Editor editor = settings.edit();
			editor.putString("oauth_token", result.getString("oauth_token"));
			editor.putString("oauth_token_secret", result.getString("oauth_token_secret"));
			editor.putString("userid", result.getString("userid"));
			editor.putString("methods", result.getString("methods"));
			editor.putString("expiredate", result.getString("expiredate"));
			editor.commit();
			
			Intent i = new Intent(this, HyvesFotolijstje.class);
			i.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
			startActivity(i);
		} catch (GeneralSecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (HyvesApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	        
            // See step 6
        }
        
    }
}